package com.samp.solr;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.*;

import org.apache.lucene.util.SmallFloat;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.NamedList;

import com.samp.util.DateUtils;

public class SolrjClient {

    //private final static String SOLR_URL = "http://120.52.78.149:8080/solr/paus";
    
    private final static String SOLR_URL = "http://localhost:8080/solr/test";

    private static List<String> getDocList(String path){
        URL url = SolrjClient.class.getClassLoader().getResource(path);
        System.out.println(url.getFile());
        File file = new File(url.getFile());
        BufferedReader reader = null;
        List<String> solrData = new ArrayList<String>();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null){
                solrData.add(tempString);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                }catch(IOException e1){
                    e1.printStackTrace();
                }
            }
        }
        return solrData;
    }

    public static void addDoc() throws SolrServerException, IOException{

        HttpSolrClient solr = new HttpSolrClient.Builder(SOLR_URL).build();
        String path = "solr/data_sim01.txt";
        try {
            List<String> solrData = getDocList(path);
            for( int i = 0; i < solrData.size(); i++ ) {
                SolrInputDocument document = new SolrInputDocument();
                document.addField("id", UUID.randomUUID().toString());
                document.addField("content", solrData.get(i));
                document.addField("contentFullMatch", solrData.get(i));
                document.addField("intention", "intention_"+i);
                solr.add(document);
            }
            solr.commit();
        } finally{
            solr.close();
        }
    }
    
    public static void addTitleDoc() throws SolrServerException, IOException{

        HttpSolrClient solr = new HttpSolrClient.Builder(SOLR_URL).build();
        String path = "com/samp/solr/data_title01.txt";
        try {
            List<String> solrData = getDocList(path);
            for( int i = 0; i < solrData.size(); i++ ) {
                SolrInputDocument document = new SolrInputDocument();
                String[] str = solrData.get(i).split("\\|");
                document.addField("id", i);
                document.addField("title", str[0]);
                document.addField("desc", str[1]);
                solr.add(document);
            }
            solr.commit();
        } finally{
            solr.close();
        }
    }
    
    public static void deleteDoc(String param) throws SolrServerException, IOException{
    	 HttpSolrClient solr = new HttpSolrClient.Builder(SOLR_URL).build();
    	 solr.deleteByQuery(param);
    	 solr.commit();
    	 solr.close();
    }
    
    @SuppressWarnings("rawtypes")
	public static void queryByDate(Date start, Date end) throws SolrServerException, IOException{
    	String solrDateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    	HttpSolrClient solrclient =  new HttpSolrClient.Builder(SOLR_URL).build();
        SolrQuery query = new SolrQuery();
        System.out.println(query.getRequestHandler());
        query.set("q", "*:*");
        StringBuilder dataFq = new StringBuilder("createddate:[");
        if( start == null ){
        	dataFq.append("*");
        }else{
        	dataFq.append(DateUtils.formatDate(toUtcDate(start), solrDateFormat));
        }
        dataFq.append(" TO ");
        if( end == null ){
        	dataFq.append("*");
        }else{
        	dataFq.append(DateUtils.formatDate(toUtcDate(end), solrDateFormat));
        }
        dataFq.append("]");
        System.out.println("dataFq = "+dataFq.toString());
        query.addFilterQuery(dataFq.toString());
        query.setStart(0);
        query.setRows(10);
        QueryResponse response = solrclient.query(query);
        SolrDocumentList solrDocumentList = response.getResults();
        //NamedList，一个有序的name/value容器，NamedList不像Map
        NamedList list = (NamedList) response.getResponse().get("highlighting");
        System.out.println(list);
        System.out.println("查询的结果");
        System.out.println("总数量：" + solrDocumentList.getNumFound());
        //遍历列表
        for (SolrDocument doc : solrDocumentList) {
        	  System.out.println("id:"+doc.get("id")+" title:"+doc.get("title")+" createddate="+DateUtils.formatDate((Date)doc.get("createddate")));
        }
    }
    
    /**
     * 将上海时区转换成utc时区
     * @param date
     * @return
     */
    private static Date toUtcDate(Date date){
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(date);
    	calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) - 8);
    	return calendar.getTime();
    }
    
    
    /**
     * 查询
     * @throws Exception
     */
    @SuppressWarnings({ "rawtypes" })
    public static void querySolr() throws Exception{
        HttpSolrClient solrclient =  new HttpSolrClient.Builder(SOLR_URL).build();
        SolrQuery query = new SolrQuery();
        //query.setRequestHandler("/mlt"); 默认是/select.
        query.add("defType","edismax");//设置查询方式为edismax，支持qf和mm参数。
        query.set("q","好");

        //参数fq, 给query增加过滤查询条件
        query.addFilterQuery("id:[0 TO 9]");//id为0-9  //参数df,给query设置默认搜索域
        query.set("df", "name");

        //参数sort,设置返回结果的排序规则
        query.setSort("id", SolrQuery.ORDER.desc);

        //设置分页参数
        query.setStart(0);
        query.setRows(10);//每一页多少值

        //参数hl,设置高亮
        query.setHighlight(true);
        //设置高亮的字段
        query.addHighlightField("name");
        //设置高亮的样式
        query.setHighlightSimplePre("<font color='red'>");
        query.setHighlightSimplePost("</font>");

        //获取查询结果
        QueryResponse response = solrclient.query(query);
        //两种结果获取：得到文档集合或者实体对象

        //查询得到文档的集合
        SolrDocumentList solrDocumentList = response.getResults();
        //NamedList，一个有序的name/value容器，NamedList不像Map
        NamedList list = (NamedList) response.getResponse().get("highlighting");
        System.out.println(list);
        System.out.println("查询的结果");
        System.out.println("总数量：" + solrDocumentList.getNumFound());
        //遍历列表
        for (SolrDocument doc : solrDocumentList) {
            System.out.println("id:"+doc.get("id")+" title:"+doc.get("title"));
        }

    }
    
    public static void addDynamicField() throws IOException{
    	HttpSolrClient solr = new HttpSolrClient.Builder(SOLR_URL).build();
        try {
            for( int i = 0; i < 5; i++ ) {
                SolrInputDocument document = new SolrInputDocument();
                document.addField("id", i);
                document.addField("id_s", "0000000"+i);
                document.addField("id_i", i*100);
                document.addField("id_d", i*0.001);
                solr.add(document);
            }
            solr.commit();
        }catch(Exception e){
        	e.printStackTrace();
        }finally{
            solr.close();
        }
    }
    
    public static void test(){
    	System.out.println(Float.isInfinite(1000f));
    	System.out.println("===="+ SmallFloat.floatToByte315(0.99999333333f));
    }
    public static void main(String[] args) {
        try {
            //querySolr();
        	String param = "frequentItem:*";
        	param = "id:*";
        	deleteDoc(param);
//        	addTitleDoc();
           addDoc();
        	//test();
//        	Date start = DateUtils.parseDate("2018-09-01 00:00:00");
//        	Date end =  DateUtils.parseDate("2018-09-07 15:59:59");;
//        	queryByDate(start, end);
//        	addDynamicField();
        }catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("done");
    }
}
